<template>
  <!-- 登录弹窗 - 使用uni-popup -->
  <uni-popup ref="loginPopup" type="bottom" :mask-click="false" :safe-area="false" :z-index="9999">
    <view class="login-popup-content">
      <view class="login-close" @click="closeModal">✕</view>
      <view class="login-header">
        <view class="app-icon">
          <image class="app-icono-img" src="/static/seach5.png" mode=""></image>
        </view>
        <text class="app-name">Solve X</text>
      </view>
      <view class="login-body">
        <view class="agreement-section">
          <view class="checkbox-container">
            <view class="checkbox" :class="{ checked: agreementChecked }" @click="toggleAgreement">
              <text class="checkmark" v-if="agreementChecked">✓</text>
            </view>
            <text class="agreement-text">
              阅读并同意
              <text class="link-text" @click="openPrivacyPolicy">隐私政策</text>、
              <text class="link-text" @click="openUserAgreement">用户协议</text>。
              若您未注册,将为您直接注册账号。
            </text>
          </view>
        </view>
      </view>
      <view class="login-actions">
        <button class="login-btn skip-btn" @click="skipLogin">暂不登录</button>
        <button class="login-btn login-btn-primary" @click="doLogin">立即登录</button>
      </view>
    </view>
  </uni-popup>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { AUTH_API } from '../../config/api.js'
import { setUserLogin } from '../../utils/user.js'

// 定义组件事件
const emit = defineEmits<{
  close: []
  skip: []
  login: []
  openPrivacyPolicy: []
  openUserAgreement: []
}>()

// 响应式数据
const agreementChecked = ref(false)
const loginPopup = ref()

// 判断当前页面是否为TabBar页面
const isTabBarPage = () => {
  const pages = getCurrentPages()
  if (pages.length === 0) return false

  const currentPage = pages[pages.length - 1]
  const currentRoute = currentPage.route

  // 根据pages.json配置，只有这两个页面是TabBar页面
  const tabBarPages = ['pages/index/index', 'pages/profile/profile']
  return tabBarPages.includes(currentRoute)
}

// 暴露给父组件的方法
const open = () => {
  loginPopup.value.open()
  // 只在TabBar页面才隐藏TabBar
  if (isTabBarPage()) {
    uni.hideTabBar()
  }
}

const close = () => {
  // 只在TabBar页面才显示TabBar
  if (isTabBarPage()) {
    uni.showTabBar()
  }
  loginPopup.value.close()
}

// 内部方法
const closeModal = () => {
  close()
  emit('close')
}

const toggleAgreement = () => {
  agreementChecked.value = !agreementChecked.value
}

const openPrivacyPolicy = () => {
  uni.navigateTo({
    url: '/pages/privacy-policy/privacy-policy'
  })
}

const openUserAgreement = () => {
  uni.navigateTo({
    url: '/pages/user-agreement/user-agreement'
  })
}

const skipLogin = () => {
  closeModal()
  emit('skip')
}

const doLogin = () => {
  if (!agreementChecked.value) {
    uni.showToast({
      title: '请先同意用户协议',
      icon: 'none',
      duration: 2000
    })
    return
  }

  // 同意完隐私协议后调用微信登录
  wechatLogin()
}

// 微信登录
const wechatLogin = () => {
  uni.showLoading({
    title: '微信登录中...'
  })

  uni.login({
    provider: "weixin",
    onlyAuthorize: true, // 微信登录仅请求授权认证
    success: (event) => {
      console.log('微信登录成功，获取到code:', event.code);
      const { code } = event;

      // 调用后端微信登录接口
      callWechatLoginAPI(code);
    },
    fail: (error) => {
      console.error('微信登录失败:', error);
      uni.hideLoading();
      uni.showToast({
        title: '微信登录失败',
        icon: 'error'
      });
    }
  });
}

// 从本地缓存获取邀请人ID
const getInviterIdFromCache = () => {
  try {
    // 从本地缓存读取inviter_id（首页已缓存）
    const inviterId = uni.getStorageSync('inviter_id') || ''
    console.log('从缓存获取到的邀请人ID:', inviterId)

    return inviterId ? parseInt(inviterId) : 0
  } catch (error) {
    console.error('从缓存获取邀请人ID失败:', error)
    return 0
  }
}

// 调用微信登录API
const callWechatLoginAPI = async (code) => {
  try {
    // 从缓存获取邀请人ID
    const inviterId = getInviterIdFromCache()

    // 构建请求参数
    const loginData = {
      code: code,
      inviter_id: inviterId  // 从缓存中获取的邀请人ID
    };

    console.log('微信登录请求参数:', loginData);

    // 调用微信登录API
    const response = await uni.request({
      url: AUTH_API.WECHAT_LOGIN,
      method: 'POST',
      header: {
        'Content-Type': 'application/json'
      },
      data: loginData
    });

    console.log('微信登录响应:', response);

    uni.hideLoading();

    if (response.statusCode === 200 && response.data.code === 200) {
      // 登录成功
      const { token, user_info } = response.data.data;

      console.log("token=========="+token);
      console.log("user_info=========="+JSON.stringify(user_info));
      // 调用auth.js的setUserLogin函数保存登录信息
      setUserLogin(token, user_info);

      uni.showToast({
        title: '微信登录成功',
        icon: 'success'
      });

      // 关闭弹窗并触发登录成功事件
      closeModal();
      emit('login');

    } else {
      // 登录失败
      throw new Error(response.data?.data?.error_message || response.data?.error_message || response.data?.message || '微信登录失败');
    }

  } catch (error) {
    console.error('微信登录API调用失败:', error);
    uni.hideLoading();
    uni.showToast({
      title: error.message || '微信登录失败',
      icon: 'error'
    });
  }
}

// 暴露方法给父组件
defineExpose({
  open,
  close
})
</script>

<style scoped>
.app-icono-img {
  width: 122rpx;
  height: 122rpx;
}

/* 登录弹窗 - uni-popup内容 */
.login-popup-content {
  background: white;
  border-radius: 24rpx 24rpx 0 0;
  padding: 40rpx;
  position: relative;
  width: 100%;
  min-height: 450rpx;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  /* 确保没有底部空白 */
  margin-bottom: 0;
  padding-bottom: 40rpx;
  z-index: 10000;
}

.login-close {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  font-size: 40rpx;
  color: #333;
  font-weight: bold;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-header {
  text-align: center;
  margin-bottom: 30rpx;
  margin-top: 20rpx;
}

.app-icon {
  width: 122rpx;
  height: 122rpx;
  border-radius: 24rpx;
  margin: 0 auto 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.app-name {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.login-body {
  margin-bottom: 30rpx;
  flex: 1;
}

.agreement-section {
  margin-bottom: 20rpx;
}

.checkbox-container {
  display: flex;
  align-items: flex-start;
  gap: 16rpx;
}

.checkbox {
  width: 40rpx;
  height: 40rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  margin-top: 4rpx;
}

.checkbox.checked {
  background: #007AFF;
  border-color: #007AFF;
}

.checkmark {
  color: white;
  font-size: 24rpx;
  font-weight: bold;
}

.agreement-text {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  flex: 1;
}

.link-text {
  color: #007AFF;
  text-decoration: underline;
}

.login-actions {
  display: flex;
  gap: 20rpx;
  margin-top: auto;
  padding-top: 20rpx;
}

.login-btn {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  box-sizing: border-box;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 600;
  border: none;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.skip-btn {
  background: #f5f5f5;
  color: #5b5b5b;
}

.login-btn-primary {
  background: #565FFD;
  color: white;
}

.login-btn:active {
  transform: translateY(2rpx);
}

/* 覆盖uni-popup的默认样式，去除底部空白 */
:deep(.uni-popup__wrapper) {
  padding-bottom: 0 !important;
  z-index: 9999 !important;
}

:deep(.uni-popup__wrapper.bottom) {
  padding-bottom: 0 !important;
  z-index: 9999 !important;
}

/* 确保弹窗内容紧贴底部 */
:deep(.uni-popup) {
  padding-bottom: 0 !important;
  z-index: 9999 !important;
}

:deep(.uni-popup__mask) {
  z-index: 9998 !important;
}

/* 确保弹窗内容在最顶层 */
:deep(.uni-popup__content) {
  z-index: 10000 !important;
  position: relative;
}

/* 确保弹窗内容能够填满整个区域 */
.login-popup-content::after {
  content: '';
  flex: 1;
  min-height: 20rpx;
}

/* 针对不同屏幕尺寸的适配 */
@media screen and (max-height: 600px) {
  .login-popup-content {
    min-height: 350rpx;
  }
  
  .login-header {
    margin-bottom: 20rpx;
  }
  
  .login-body {
    margin-bottom: 20rpx;
  }
  
  .login-actions {
    padding-top: 10rpx;
  }
}
</style>
